package com.zhisheng.mygateway.filter;

/*
    全哥

    专门负责在网关中对令牌进行校验,如果令牌合法,则继续向后转发到具体的微服务中,如果令牌不合法则不是登陆和注册的路径,则直接返回,无需再进行转发了!!!

*/

import com.zhisheng.mygateway.utils.MyJwtUtils_0_9_1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyJwtChecker implements GlobalFilter{

    @Autowired
    private MyJwtUtils_0_9_1 myJwtUtils_0_9_1;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1: 获取请求的路径
        ServerHttpRequest request = exchange.getRequest();
        String requestURI = request.getURI().getPath();
        // 2: 判断,如果是登陆或注册,则放行
        if (requestURI.contains("/users/login") || requestURI.contains("/users/register")) {
            return chain.filter(exchange);
        }
        //3: 如果是其他路径,则获取令牌并校验真伪
        /*String token = request.getHeaders().getFirst("token");
        String fromToken = myJwtUtils_0_9_1.getClaimsFromToken(token);
        if ("令牌解析失败!".equals(fromToken) ) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().setContentType(MediaType.TEXT_PLAIN);

            String message = "请先登陆";
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }*/
        // 4: 将令牌中的字符串信息,通过请求头,交给后面的具体的微服务
        ServerHttpRequest mutatedRequest = request.mutate()
                .header("loginUser", "{\"id\":5,\"isDel\":0,\"password\":\"123\",\"username\":\"zs\"}") // 这里添加 token 请求头，值为 "123"
                .build();
        ServerWebExchange mutatedExchange = exchange.mutate()
                .request(mutatedRequest)
                .build();

        return chain.filter(mutatedExchange);

    }
}
